package com.ruoyi.device.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @Author wy
 * @Description mybatis-plus(save,update操作的时候，某些字段)自动填充功能
 * @Date 2023/11/13 9:49
 * @Version 1.0
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    /**
     *  @TableField(.. fill = FieldFill.INSERT)
     * 新增
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.nonNull(loginUser)){
            this.strictInsertFill(metaObject, "createBy", String.class, loginUser.getUsername());
        }


    }

    /**
     *  @TableField(.. fill = FieldFill.UPDATE)
     * 修改
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.nonNull(loginUser)){
            this.strictUpdateFill(metaObject, "updateBy", String.class, loginUser.getUsername());
        }



    }
}
